public class AddContractAmountController {

    private List<ContractAmount__c> ContractAmountList = new List<ContractAmount__c>();
    private List<String> Months = new List<String>();
    private Contract objContract;
    public String ContractName{set;get;}
    ContractAmount__c[] contractAmount;
    public void setContractAmountList(List<ContractAmount__c> setterList){
    	ContractAmountList.addAll(setterList);
    }
    public List<ContractAmount__c> getContractAmountList(){
    	return ContractAmountList;
    }
    
    public AddContractAmountController(ApexPages.StandardController controller) {
		objContract = (Contract)controller.getRecord();
		Contract contract = [select ContractNumber, StartDate, ContractTerm from Contract where Id=: objContract.Id];
		contractAmount = [Select ContractMonth__c,Amount_1__c, Amount_2__c from ContractAmount__c where Contract__c =:objContract.Id ];
		Months.add('Jan');Months.add('Feb');Months.add('March');Months.add('April');
		Months.add('May');Months.add('June');Months.add('July');Months.add('Aug');
		Months.add('Sep');Months.add('Oct');Months.add('Nov');Months.add('Dec');
		ContractName = contract.ContractNumber;
		if(contractAmount.size()>0){
			ContractAmountList.addAll(contractAmount);
		}
		else{
			ContractAmountList.clear();
			Integer startMonth = (contract.StartDate).month()-1;
			Integer startYear = (contract.StartDate).year();
			for(Integer i=0; i<contract.ContractTerm; i++){
				ContractAmount__c obj = new ContractAmount__c();
				obj.Amount_1__c =0;
				obj.Amount_2__c =0;
				if(startMonth>11){
					startMonth=0;
					startYear++;
				}
				obj.ContractMonth__c = Months.get(startMonth)+'-'+String.valueOf(startYear);
				obj.Contract__c = objContract.Id;
				startMonth++;
				ContractAmountList.add(obj);
			}
		}
    }
    
    public PageReference updateContract(){
    	if(contractAmount.size()>0){
    		update(ContractAmountList);
    	}
    	else{
    		insert(ContractAmountList);
    	}
    	return (new PageReference('/'+objContract.id));
    }
}